package dj.action;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import dj.Constant;
import dj.action.base.BaseAction;
import dj.model.CompanyReport;
import dj.model.ZhebiaoXishu;
import dj.pageModel.Json;
import dj.pageModel.PcompanyReport;
import dj.pageModel.Puser;
import dj.pageModel.PzhebiaoXishu;
import dj.service.CompanyReportService;
import dj.service.SysRoleService;
import dj.service.ZhebiaoxishuService;

@Action(value = "companyReportAction", results = { @Result(name = "reportView", location = "/app/company/datareport/data_report.jsp") })
public class CompanyReportAction extends BaseAction implements ModelDriven<PcompanyReport> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CompanyReportAction.class);

	private PcompanyReport pr = new PcompanyReport();

	private ZhebiaoxishuService zhebiaoService;

	private CompanyReportService companyReportService;

	private SysRoleService sysRoleService;

	public PcompanyReport getModel() {
		return pr;
	}

	public ZhebiaoxishuService getZhebiaoService() {
		return zhebiaoService;
	}

	@Autowired
	public void setZhebiaoService(ZhebiaoxishuService zhebiaoService) {
		this.zhebiaoService = zhebiaoService;
	}

	public CompanyReportService getCompanyReportService() {
		return companyReportService;
	}

	@Autowired
	public void setCompanyReportService(CompanyReportService companyReportService) {
		this.companyReportService = companyReportService;
	}

	public SysRoleService getSysRoleService() {
		return sysRoleService;
	}

	@Autowired
	public void setSysRoleService(SysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}

	public void getReportTask() {
		Map<String, Object> taskMap = new HashMap<String, Object>();

		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		String p = ServletActionContext.getRequest().getParameter("page");
		String r = ServletActionContext.getRequest().getParameter("rows");
		int page = 0;
		int rows = 0;
		try {
			page = Integer.parseInt(p);
			rows = Integer.parseInt(r);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		}

		List<PcompanyReport> prs = new ArrayList<PcompanyReport>();

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, String> conditions = new HashMap<String, String>();
			params.put("cr.creatorid", loginUser.getId());
			conditions.put("cr.creatorid", "=");
			if (null != pr.getUsername() && !"".equals(pr.getUsername().trim())) {
				params.put("cr.username", "%" + pr.getUsername() + "%");
				conditions.put("cr.username", "like");
			}
			if (null != pr.getTaskmonth() && !"".equals(pr.getTaskmonth().trim())) {
				params.put("cr.taskmonth", pr.getTaskmonth());
				conditions.put("cr.taskmonth", "=");
			}

			long userNum = companyReportService.getCompanyReportTaskNum(null, null, params, conditions);
			prs = companyReportService.getCompanyReportTask(null, null, params, conditions, page, rows, null);

			taskMap.put("total", userNum);
			taskMap.put("rows", prs);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}

		super.writeToJson(taskMap, "yyyy-MM-dd");
	}

	public void createReportTask() {
		Json j = new Json();

		String[] companys = ServletActionContext.getRequest().getParameterValues("companys");
		if (null != companys && companys.length > 0) {
			ZhebiaoXishu zx = zhebiaoService.getZhebiaoxishuByStatus(PzhebiaoXishu.STATUS_OPEN);
			if (null == zx) {
				j.setMsg("请先配置折标系数！");
			} else {
				try {
					companyReportService.createReportTask(pr, zx);
					j.setSuccess(true);
					j.setMsg("任务创建成功！");
				} catch (Exception e) {
					j.setMsg("创建任务失败！");
					logger.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}

		super.writeToJson(j);
	}

	public void updateCompanyTaskDate() {
		Json j = new Json();
		if (null != pr.getStartDate() && null != pr.getEndDate()) {
			try {
				companyReportService.updateTaskDate(pr);
				j.setSuccess(true);
				j.setMsg("更新日期成功！");
			} catch (Exception e) {
				j.setMsg("更新日期失败！");
				logger.error(e.getMessage());
				e.printStackTrace();
			}
		} else {
			j.setMsg("开始日期和结束日期不能为空！");
		}

		super.writeToJson(j);
	}

	public void deleteCompanyTask() {
		Json j = new Json();
		String ids = ServletActionContext.getRequest().getParameter("ids");
		if (null != ids) {
			String[] id = ids.split(",");
			if (null != id && id.length > 0) {
				try {
					companyReportService.deleteTasks(id);
					j.setSuccess(true);
					j.setMsg("删除任务成功！");
				} catch (Exception e) {
					j.setMsg("删除任务失败！");
					logger.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}

		super.writeToJson(j);
	}

	/**
	 * 根据状态和查询条件 获取企业报表列表
	 */
	public void getCompanyReportListByCompany() {
		Map<String, Object> taskMap = new HashMap<String, Object>();

		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		String p = ServletActionContext.getRequest().getParameter("page");
		String r = ServletActionContext.getRequest().getParameter("rows");
		int page = 0;
		int rows = 0;
		try {
			page = Integer.parseInt(p);
			rows = Integer.parseInt(r);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		}

		List<PcompanyReport> prs = new ArrayList<PcompanyReport>();

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, String> conditions = new HashMap<String, String>();
			params.put("cr.userid", loginUser.getId());
			conditions.put("cr.userid", "=");
			if (null != pr.getTaskmonth() && !"".equals(pr.getTaskmonth().trim())) {
				params.put("cr.taskmonth", pr.getTaskmonth());
				conditions.put("cr.taskmonth", "=");
			}

			List<String> statuss = new ArrayList<String>();
			if (null == pr.getStatus()) {
				statuss.add(PcompanyReport.STRUTS_未填写);
				statuss.add(PcompanyReport.STRUTS_未提交);
				statuss.add(PcompanyReport.STRUTS_未通过);
			} else {
				statuss.add(pr.getStatus());
			}

			long taskNum = companyReportService.getCompanyReportTaskNum(statuss, null, params, conditions);
			prs = companyReportService.getCompanyReportTask(statuss, null, params, conditions, page, rows, null);

			taskMap.put("total", taskNum);
			taskMap.put("rows", prs);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}

		super.writeToJson(taskMap, "yyyy-MM-dd");
	}
	
	public void getWaitAuditReport() {
		Map<String, Object> auditMap = new HashMap<String, Object>();

		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		String p = ServletActionContext.getRequest().getParameter("page");
		String r = ServletActionContext.getRequest().getParameter("rows");
		int page = 0;
		int rows = 0;
		try {
			page = Integer.parseInt(p);
			rows = Integer.parseInt(r);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		}

		List<PcompanyReport> prs = new ArrayList<PcompanyReport>();

		try {
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, String> conditions = new HashMap<String, String>();
			params.put("cr.creatorid", loginUser.getId());
			conditions.put("cr.creatorid", "=");
			if (null != pr.getTaskmonth() && !"".equals(pr.getTaskmonth().trim())) {
				params.put("cr.taskmonth", pr.getTaskmonth());
				conditions.put("cr.taskmonth", "=");
			}
			List<String> companyls = new ArrayList<String>();
			if(null != pr.getUserid() && !"".equals(pr.getUserid())) {
				String[] companys = pr.getUserid().split(",");
				if(null != companys && companys.length > 0) {
					for(String company : companys) {
						companyls.add(company);
					}
				}
			}
			
			List<String> statuss = new ArrayList<String>();
			statuss.add(PcompanyReport.STRUTS_未审核);

			long waitAuditNum = companyReportService.getCompanyReportTaskNum(statuss, companyls, params, conditions);
			prs = companyReportService.getCompanyReportTask(statuss, companyls, params, conditions, page, rows, null);

			auditMap.put("total", waitAuditNum);
			auditMap.put("rows", prs);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}

		super.writeToJson(auditMap, "yyyy-MM-dd");
	}

	public String toReportPage() {
		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		if (null != pr.getId() && !"".equals(pr.getId().trim())) {
			CompanyReport cr = companyReportService.get(pr.getId());
			if (null != cr) {
				if (cr.getUserid().equals(loginUser.getId()) || cr.getCreatorid().equals(loginUser.getId())) {
					PcompanyReport ppr = new PcompanyReport();
					PzhebiaoXishu px = new PzhebiaoXishu();
					ppr.setPzhebiaoXishu(px);

					BeanUtils.copyProperties(cr, ppr);
					BeanUtils.copyProperties(cr.getZhebiaoXishu(), ppr.getPzhebiaoXishu());
					ServletActionContext.getRequest().setAttribute("pageCompanyReport", ppr);
				} else {
					ServletActionContext.getRequest().setAttribute("msg", "您没有权限访问该报表！");
					return "error";
				}
			} else {
				ServletActionContext.getRequest().setAttribute("msg", "报表不存在！");
				return "error";
			}
		}

		return "reportView";
	}

	public void saveReport() {
		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		Json j = new Json();
		boolean validateStatus = true;
		CompanyReport cr = companyReportService.get(pr.getId());
		if (null != cr) {
			if (cr.getUserid().equals(loginUser.getId())) {
				if (PcompanyReport.STRUTS_未审核.equals(pr.getStatus())) {
					if (!PcompanyReport.STRUTS_未填写.equals(cr.getStatus()) && !PcompanyReport.STRUTS_未通过.equals(cr.getStatus()) && !PcompanyReport.STRUTS_未提交.equals(cr.getStatus())) {
						j.setMsg("提交失败，当前非可提交状态！");
						validateStatus = false;
					}
				}
				if (validateStatus) {
					// 当前为未填写状态，保存后改为未提交状态
					if (null == pr.getStatus()) {
						pr.setStatus(PcompanyReport.STRUTS_未提交);
					} else if (!PcompanyReport.STRUTS_未审核.equals(pr.getStatus())) {
						j.setMsg("提交失败，非法的状态！");
						validateStatus = false;
					}
					if (validateStatus) {
						pr.setCreatorid(cr.getCreatorid());
						pr.setCreatorname(cr.getCreatorname());
						pr.setUserid(cr.getUserid());
						pr.setUsername(cr.getUsername());
						pr.setCreateDate(cr.getCreateDate());
						pr.setSubmitTime(new Timestamp(new Date().getTime()));
						pr.setTaskmonth(cr.getTaskmonth());
						pr.setStartDate(cr.getStartDate());
						pr.setEndDate(cr.getEndDate());

						try {
							BeanUtils.copyProperties(pr, cr);
							companyReportService.update(cr);
							j.setSuccess(true);
							j.setMsg("操作成功！");
						} catch (BeansException e) {
							j.setMsg("操作失败，请稍后再试！");
							logger.error(e.getMessage());
							e.printStackTrace();
						}
					}
				}
			} else {
				j.setMsg("您没有权限操作该报表！");
			}
		} else {
			j.setMsg("该报表不存在！");
		}

		super.writeToJson(j);
	}

	public void changeReportStatus() {
		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		Json j = new Json();
		CompanyReport cr = companyReportService.get(pr.getId());
		boolean validateRole = true;
		if (null != cr) {
			if (cr.getUserid().equals(loginUser.getId()) || cr.getCreatorid().equals(loginUser.getId())) {
				if(PcompanyReport.STRUTS_未审核.equals(cr.getStatus())) {
					//如果状态要改为已通过，或未通过，则必须是数据管理员权限
					if(PcompanyReport.STRUTS_已通过.equals(pr.getStatus()) || PcompanyReport.STRUTS_未通过.equals(pr.getStatus())) {
						if(!sysRoleService.isSysRole(loginUser.getId(), Constant.SYSROLE_MEMBER_TYPE_USER, "数据管理员")) {
							validateRole = false;
							j.setMsg("您没有权限执行该操作！");
						}
					} else if(!PcompanyReport.STRUTS_未提交.equals(pr.getStatus())) {
						if(!sysRoleService.isSysRole(loginUser.getId(), Constant.SYSROLE_MEMBER_TYPE_USER, "企业数据员")) {
							validateRole = false;
							j.setMsg("您没有权限执行该操作！");
						}
					} else {
						validateRole = false;
						j.setMsg("非法的状态！");
					}
					
					if(validateRole) {
						cr.setStatus(pr.getStatus());
						try {
							companyReportService.update(cr);
							j.setSuccess(true);
							j.setMsg("操作成功！");
						} catch (BeansException e) {
							j.setMsg("操作失败，请稍后再试！");
							logger.error(e.getMessage());
							e.printStackTrace();
						}
					}
				} else {
					j.setMsg("当前状态无法更改！");
				}
			} else {
				j.setMsg("您没有权限操作该报表！");
			}
		} else {
			j.setMsg("该报表不存在！");
		}

		super.writeToJson(j);
	}
}
